import React, { FC, useEffect } from 'react';
import { Modal, Form, InputNumber, Input} from 'antd';
import { StudyCatalogItem } from '@/services/study/catalog';

interface OperationModalProps {
  open: boolean;
  studyCatalogItem: Partial<StudyCatalogItem> | undefined;
  onSubmit: (values: StudyCatalogItem) => void;
  onCancel: () => void;
}

const formLayout = {
  labelCol: { span: 7 },
  wrapperCol: { span: 13 },
};

const StudyCatalogForm: FC<OperationModalProps> = (props) => {
  const [form] = Form.useForm();
  const { open, studyCatalogItem, onCancel, onSubmit } = props;

  useEffect(() => {
    if (form && !open) {
      form.resetFields();
    }
  }, [props.open]);

  useEffect(() => {
    if (studyCatalogItem) {
      form.setFieldsValue({
        ...studyCatalogItem,
      });
    }
  }, [props.studyCatalogItem]);

  const handleSubmit = () => {
    if (!form){
      return;
    } 
    form.submit();
  };

  const handleFinish = (values: { [key: string]: any }) => {
    if (onSubmit) {
      onSubmit({ ...values } as StudyCatalogItem);
    }
  };

  const modalFooter = { okText: '保存', onOk: handleSubmit, onCancel };

  const renderContent = () => {
    return (
      <>
        <Form.Item
          label="名称"
          name="name"
          rules={[{ required: true, message: '请输入名称' }]}
        >
          <Input placeholder="请输入名称" />
        </Form.Item>
        <Form.Item 
          label="排序"
          name="sortNum"
          rules={[{ required: true, message: '请输入排序' }]}
        >
          <InputNumber
            style={{ width: '100%' }}
            max={100}
            step={1}
          />
        </Form.Item>
        <Form.Item label="备注" name="remark">
          <Input.TextArea rows={4} placeholder="请输入备注" />
        </Form.Item>
        <Form.Item hidden={true} name="id">
          <Input hidden={true} />
        </Form.Item>
        <Form.Item hidden={true} name="parentid">
          <Input hidden={true} />
        </Form.Item>
      </>
    );
  };

  return (
    <Modal
      title={`${
        studyCatalogItem?.optType === 'edit'
          ? '编辑目录'
          : studyCatalogItem?.optType === 'add'
          ? '添加目录'
          : '添加子目录'
      }`}
      width={640}
      destroyOnClose
      open={open}
      {...modalFooter}
    >
      <Form {...formLayout} form={form} onFinish={handleFinish}>
        {renderContent()}
      </Form>
    </Modal>
  );
};

export default StudyCatalogForm;
